<template>
  <div class="cascader-table-example">
    <div class="header">
      <h1>🔗 级联选择器与表格联动示例</h1>
      <p>演示如何将级联选择器的值传递给父组件，并作为表格请求参数</p>
    </div>

    <!-- 级联选择器区域 -->
    <div class="selector-section">
      <h2>📋 选择筛选条件</h2>
      <div class="form-group">
        <label>选择组件分类：</label>
        <CascaderSelect
          v-model="selectedValue"
          :options="options"
          placeholder="请选择分类筛选条件"
          @change="handleCascaderChange"
        />
      </div>
      
      <!-- 显示当前选中信息 -->
      <div class="selected-info" v-if="selectedValue.length">
        <h3>🎯 当前选中信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">完整路径：</span>
            <span class="value">{{ selectedLabels.join(' → ') }}</span>
          </div>
          <div class="info-item">
            <span class="label">请求参数值：</span>
            <span class="value highlight">{{ requestParam }}</span>
          </div>
          <div class="info-item">
            <span class="label">参数说明：</span>
            <span class="value">使用最深层级的 name 值</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <h2>📊 数据表格</h2>
      
      <!-- 请求参数显示 -->
      <div class="request-info">
        <h3>🔧 模拟请求信息</h3>
        <div class="request-details">
          <div class="request-item">
            <span class="label">请求URL：</span>
            <code>/api/table/data</code>
          </div>
          <div class="request-item">
            <span class="label">请求参数：</span>
            <code>{{ getRequestParams() }}</code>
          </div>
          <div class="request-item">
            <span class="label">请求状态：</span>
            <span :class="['status', loading ? 'loading' : 'success']">
              {{ loading ? '🔄 加载中...' : '✅ 请求成功' }}
            </span>
          </div>
        </div>
      </div>

      <!-- 表格内容 -->
      <div class="table-container">
        <table class="data-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>名称</th>
              <th>分类</th>
              <th>描述</th>
              <th>创建时间</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading">
              <td colspan="6" class="loading-cell">🔄 数据加载中...</td>
            </tr>
            <tr v-else-if="!tableData.length">
              <td colspan="6" class="empty-cell">📭 暂无数据，请选择筛选条件</td>
            </tr>
            <tr v-else v-for="item in tableData" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.category }}</td>
              <td>{{ item.description }}</td>
              <td>{{ item.createTime }}</td>
              <td>
                <span :class="['status-tag', item.status]">
                  {{ item.statusText }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 操作日志 -->
    <div class="log-section">
      <h2>📝 操作日志</h2>
      <div class="log-container">
        <div v-for="(log, index) in operationLogs" :key="index" class="log-item">
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
        <div v-if="!operationLogs.length" class="empty-log">
          暂无操作记录
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import CascaderSelect from './CascaderSelect.vue'
import type { CascaderOption } from './CascaderSelect.vue'

// 级联选择器数据
const options: CascaderOption[] = [
  {
    name: 'component',
    nameCn: '组件',
    nameEn: 'Component',
    children: [
      {
        name: 'basic',
        nameCn: '基础组件',
        nameEn: 'Basic',
        children: [
          { name: 'button', nameCn: '按钮', nameEn: 'Button' },
          { name: 'input', nameCn: '输入框', nameEn: 'Input' },
          { name: 'icon', nameCn: '图标', nameEn: 'Icon' },
        ]
      },
      {
        name: 'form',
        nameCn: '表单组件',
        nameEn: 'Form',
        children: [
          { name: 'select', nameCn: '选择器', nameEn: 'Select' },
          { name: 'cascader', nameCn: '级联选择器', nameEn: 'Cascader' },
          { name: 'switch', nameCn: '开关', nameEn: 'Switch' },
        ]
      },
      {
        name: 'data',
        nameCn: '数据展示',
        nameEn: 'Data',
        children: [
          { name: 'table', nameCn: '表格', nameEn: 'Table' },
          { name: 'pagination', nameCn: '分页', nameEn: 'Pagination' },
          { name: 'tree', nameCn: '树形控件', nameEn: 'Tree' },
        ]
      }
    ]
  },
  {
    name: 'guide',
    nameCn: '指南',
    nameEn: 'Guide',
    children: [
      {
        name: 'design',
        nameCn: '设计原则',
        nameEn: 'Design',
        children: [
          { name: 'consistency', nameCn: '一致性', nameEn: 'Consistency' },
          { name: 'feedback', nameCn: '反馈', nameEn: 'Feedback' },
        ]
      }
    ]
  }
]

// 响应式数据
const selectedValue = ref<string[]>([])
const selectedLabels = ref<string[]>([])
const tableData = ref<any[]>([])
const loading = ref(false)
const operationLogs = ref<Array<{time: string, message: string}>>([])

// 计算属性 - 请求参数（最深层级的name值）
const requestParam = computed(() => {
  if (!selectedValue.value.length) return ''
  return selectedValue.value[selectedValue.value.length - 1]
})

// 方法 - 处理级联选择器变更
const handleCascaderChange = (value: string[], selectedOptions: CascaderOption[]) => {
  selectedLabels.value = selectedOptions.map(opt => opt.nameCn)
  
  // 添加操作日志
  addLog(`级联选择器值变更: ${selectedLabels.value.join(' → ')}`)
  addLog(`提取请求参数: ${requestParam.value}`)
  
  // 触发表格数据请求
  if (requestParam.value) {
    fetchTableData(requestParam.value)
  } else {
    tableData.value = []
  }
}

// 方法 - 获取请求参数对象
const getRequestParams = () => {
  const params = {
    category: requestParam.value || null,
    page: 1,
    pageSize: 10
  }
  return JSON.stringify(params, null, 2)
}

// 方法 - 模拟表格数据请求
const fetchTableData = async (category: string) => {
  loading.value = true
  addLog(`开始请求表格数据，参数: category=${category}`)
  
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟不同分类的数据
    const mockData = generateMockData(category)
    tableData.value = mockData
    
    addLog(`请求完成，获取到 ${mockData.length} 条数据`)
  } catch (error) {
    addLog(`请求失败: ${error}`)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 方法 - 生成模拟数据
const generateMockData = (category: string) => {
  const dataMap: Record<string, any[]> = {
    'button': [
      { id: 1, name: '主要按钮', category: '按钮', description: '用于主要操作', createTime: '2024-01-01', status: 'active', statusText: '启用' },
      { id: 2, name: '次要按钮', category: '按钮', description: '用于次要操作', createTime: '2024-01-02', status: 'inactive', statusText: '禁用' },
      { id: 3, name: '危险按钮', category: '按钮', description: '用于危险操作', createTime: '2024-01-03', status: 'active', statusText: '启用' }
    ],
    'input': [
      { id: 4, name: '文本输入框', category: '输入框', description: '基础文本输入', createTime: '2024-01-04', status: 'active', statusText: '启用' },
      { id: 5, name: '数字输入框', category: '输入框', description: '数字专用输入', createTime: '2024-01-05', status: 'active', statusText: '启用' }
    ],
    'table': [
      { id: 6, name: '基础表格', category: '表格', description: '显示表格数据', createTime: '2024-01-06', status: 'active', statusText: '启用' },
      { id: 7, name: '可选择表格', category: '表格', description: '支持行选择', createTime: '2024-01-07', status: 'active', statusText: '启用' },
      { id: 8, name: '可编辑表格', category: '表格', description: '支持行内编辑', createTime: '2024-01-08', status: 'inactive', statusText: '禁用' }
    ],
    'select': [
      { id: 9, name: '单选选择器', category: '选择器', description: '单选下拉框', createTime: '2024-01-09', status: 'active', statusText: '启用' },
      { id: 10, name: '多选选择器', category: '选择器', description: '多选下拉框', createTime: '2024-01-10', status: 'active', statusText: '启用' }
    ]
  }
  
  return dataMap[category] || [
    { id: 999, name: `${category} 示例数据`, category: category, description: '这是模拟数据', createTime: '2024-01-01', status: 'active', statusText: '启用' }
  ]
}

// 方法 - 添加操作日志
const addLog = (message: string) => {
  const now = new Date()
  const time = now.toLocaleTimeString()
  operationLogs.value.unshift({ time, message })
  
  // 只保留最近20条日志
  if (operationLogs.value.length > 20) {
    operationLogs.value = operationLogs.value.slice(0, 20)
  }
}

// 监听选中值变化
watch(selectedValue, (newValue) => {
  console.log('级联选择器值变化:', newValue)
  console.log('请求参数:', requestParam.value)
})
</script>

<style scoped>
.cascader-table-example {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 40px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
}

.header h1 {
  margin: 0 0 10px 0;
  font-size: 2rem;
}

.header p {
  margin: 0;
  opacity: 0.9;
}

.selector-section,
.table-section,
.log-section {
  margin-bottom: 30px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 12px;
  border-left: 5px solid #667eea;
}

.selector-section h2,
.table-section h2,
.log-section h2 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #34495e;
}

.selected-info {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.selected-info h3 {
  margin: 0 0 15px 0;
  color: #667eea;
  font-size: 1.1rem;
}

.info-grid {
  display: grid;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  min-width: 120px;
  font-weight: 600;
  color: #6c757d;
}

.info-item .value {
  color: #495057;
}

.info-item .value.highlight {
  background: #e7f3ff;
  color: #667eea;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 600;
  font-family: 'Courier New', monospace;
}

.request-info {
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.request-info h3 {
  margin: 0 0 15px 0;
  color: #667eea;
  font-size: 1.1rem;
}

.request-details {
  display: grid;
  gap: 10px;
}

.request-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.request-item .label {
  min-width: 100px;
  font-weight: 600;
  color: #6c757d;
  flex-shrink: 0;
}

.request-item code {
  background: #f1f3f4;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 13px;
  white-space: pre-wrap;
  flex: 1;
}

.status.loading {
  color: #ffc107;
}

.status.success {
  color: #28a745;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th {
  background: #f8f9fa;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #495057;
  border-bottom: 1px solid #dee2e6;
}

.data-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #f1f3f4;
}

.data-table tr:hover {
  background-color: #f8f9fa;
}

.loading-cell,
.empty-cell {
  text-align: center;
  color: #6c757d;
  font-style: italic;
  padding: 40px !important;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.active {
  background: #d4edda;
  color: #155724;
}

.status-tag.inactive {
  background: #f8d7da;
  color: #721c24;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  background: white;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.log-item {
  padding: 8px 16px;
  border-bottom: 1px solid #f1f3f4;
  font-size: 13px;
  display: flex;
  gap: 12px;
}

.log-time {
  color: #6c757d;
  font-weight: 500;
  min-width: 90px;
}

.log-message {
  color: #495057;
}

.empty-log {
  padding: 20px;
  text-align: center;
  color: #6c757d;
  font-style: italic;
}

@media (max-width: 768px) {
  .cascader-table-example {
    padding: 10px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item .label {
    min-width: auto;
  }
  
  .table-container {
    overflow-x: auto;
  }
}
</style>
